Array.prototype.myReduce = function(fn, base) {
    if(typeof fn !== "function") {
        throw new TypeError(`${arguments[0]} is not a function`)
    }
    if(arguments.length == 1 && this.length == 0) {
        throw new TypeError(`Reduce of empty array with no initial value`)
    }
    let initialArr = this
    let arr = initialArr.concat() // 创建一个新的数组，不改变原数组，后续操作都在新数组上进行
    let index,newValue
    // 判断有没有传base
    if(arguments.length == 2) {
        arr.unshift(base)
        index = 0
    } else {
        index = 1
    }
    if(arr.length == 1) {  // 调用的数组为空数组，直接返回base
        newValue = arr[0]
    }
    while(arr.length > 1) {
        // 新的pre
        newValue = fn.call(null, arr[0], arr[1], index, initialArr)
        index++
        // 删除旧的pre cur，插入新的pre
        arr.splice(0,2,newValue)
    }
    return newValue
}
// let arr = [1, 2, 3, 4, 5]
let arr = new Array(3).fill()
// let val = arr.myReduce((pre, cur, index, arr) => {
//     return pre + cur
// }, -1)
let res = arr.myReduce((pre, cur, index) => {
    console.log(index, '=======', this);
    return pre + cur
}, 6)
let res1 = arr.reduce((pre, cur, index) => {
    console.log(index, '+++++', this);
    return pre + cur
    
})
console.log(res, res1);